<template>
    <div class="wrapper">
      <div style="margin: 200px auto; background-color: #fff; width: 350px; height: 300px; padding: 20px; border-radius: 10px">
        <div style="margin: 20px 0; text-align: center; font-size: 24px"><b>登 录</b></div>
        <el-form :model="user" :rules="rules" ref="userForm">
          <el-form-item prop="username">
            <el-input placeholder="请输入用户名" size="medium" style="margin: 10px 0" prefix-icon="User" v-model="user.username"></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input placeholder="请输入密码" size="medium" style="margin: 10px 0;" prefix-icon="Lock" show-password v-model="user.password"></el-input>
          </el-form-item>
          <div style="margin: 10px 0; text-align: right">
            <el-button type="primary" size="medium" autocomplete="off" @click="login(userForm)">登录</el-button>
            <el-button type="warning" size="medium" autocomplete="off" @click="$router.push('/register')">注册</el-button>
          </div>
        </el-form>
      </div>
    </div>
  </template>
  
  <script setup lang="ts">

        import {ref, reactive} from 'vue'
        import { useRouter } from 'vue-router'
        import instance from '@/utils/request'
        import { ElMessage } from 'element-plus'
        const router = useRouter()

      const user = ref({}) 

      const userForm = ref<FormInstance>()

      const rules = {
        username: [
          {required: true, message: '请输入用户名', trigger: 'blur'},
          {min: 0, max: 10, message: '长度在 0 到 10 个字符', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'},
          {min: 0, max: 20, message: '长度在 0 到 20 个字符', trigger: 'blur'}
        ]
      }
    
      const login = (formEl: FormInstance | undefined) => { 
      if (!formEl) return
        formEl.validate( async (valid) => {
          if (valid) {
            const res = await instance.post('/admin/login', user.value)
              if(res.data.code == '200'){
                ElMessage({
                  message: '登录成功',
                  type: 'success'
                })
                localStorage.setItem('user', JSON.stringify(user.value))
                router.push('manage')
              }else{
                ElMessage({
                  message: res.data.msg,
                  type: 'error'
                })
              }
          } 
        })
      }

  </script>
  
  <style scoped>
    .wrapper{
      height: 100vh;
      background-image: linear-gradient(to bottom right, #FC466B, #3F5EFB);
      overflow: hidden;
    }
  </style>